/*
 * @Author: C.
 * @Date: 2023-06-01 09:41:02
 */
import { defineStore } from 'pinia';
import { store } from '/@/store';
import { IBackMsg, IFrontMsg } from '/~/utils/wsType';
import { message_list } from '/@/api/work/system/message';
import { Ws } from '/~/utils/websocket';
// import { msgEnum } from '/@/maps/baseData/msgEnum';
import { handleNotification } from '/~/utils/help/noticeHelp';
import { INoticeMsg } from '/~/utils/wsType';
interface INotify {
  Type: string;
  MsgList: INoticeMsg[];
}

interface IWsStore {
  notifys: INotify[];
  socket: Ws;
}
export const useWsStore = defineStore({
  id: 'websocket',
  state: (): IWsStore => ({
    socket: new Ws(),
    notifys: [],
  }),
  getters: {},
  actions: {
    async setNotifys(list) {
      this.notifys = list;
    },
    async getNotifys(cb?: Fn) {
      const mlist = await message_list();
      console.log(mlist, 'mlist');

      this.setNotifys(mlist);
      cb && cb();
    },
    connect() {
      // this.socket.init(this.receiveMessages);
    },
    sendNessage(msg: IFrontMsg) {
      this.socket.send(JSON.stringify(msg));
    },

    receiveMessages(event) {
      const msg = JSON.parse(event.data) as IBackMsg;
      // const { Content, Type, NotificationType, FromUser, SendTime } = msg;
      console.log(msg, '接受消息');
      //action
      handleNotification(msg);
    },
    close() {
      this.socket.close();
    },
  },
});

// Need to be used outside the setup
export function useWsStoreWithOut() {
  return useWsStore(store);
}
